package com.badibadi.activity;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.facebook.Facebook;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.sina.weibo.SinaWeibo.ShareParams;
import cn.sharesdk.system.text.ShortMessage;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;

import com.badibadi.infos.Pre_message_total;
import com.badibadi.infos.Results;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.PhoneActivity;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.layout;
import com.badibadi.uniclubber.R.menu;
import com.libjph.util.StringUtil;
//import com.lidroid.xutils.util.LogUtils;
import com.wyy.twodimcode.CaptureActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.CursorJoiner.Result;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

/**
 * 添加朋友 saoyisao
 * 
 * @author Administrator twitter weixin
 * 
 */
public class AddFriendsActivity extends BaseActivity implements OnClickListener {

	protected static final int MSG_AUTH_ERROR = 10;
	private LinearLayout btn_saoyisao, activity_add_friends_btn;
	private Intent intent = null;
	private String erweimasourse;
	private String User = "";
	private String PhoneNumber = "";

	private ShareParams sp;
	Platform share;
	public android.os.Handler sharehanders = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {

			case 5:
				Utils.ExitPrgress(AddFriendsActivity.this);
				try {
					int num = msg.getData().getInt("num", 0);
					if (num != 1 && num != 3 && num != 4) {
						sp.setTitleUrl(msg.getData().getString("msg",
								"http://www.uniclubber.com"));
					}
					// 执行图文分享
					share.share(sp);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 6://
				Utils.ExitPrgress(AddFriendsActivity.this);
				try {
					Utils.showMessage(AddFriendsActivity.this, getResources()
							.getString(R.string.l_xb113));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case MSG_AUTH_ERROR:
				Utils.ExitPrgress(AddFriendsActivity.this);
				try {
					Utils.showMessage(AddFriendsActivity.this, getResources()
							.getString(R.string.wx_caozuo_false));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 7:
				Utils.ExitPrgress(AddFriendsActivity.this);
				try {
					Utils.showMessage(AddFriendsActivity.this, getResources()
							.getString(R.string.wx_caozuo_success));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 8:
				Utils.ExitPrgress(AddFriendsActivity.this);
				try {
					Utils.showMessage(AddFriendsActivity.this, getResources()
							.getString(R.string.wx_caozuo_success));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			}
			;
		};
	};

	// private LinearLayout qq,sinaweibo,xinxi,facebook,twitter,weixin;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		ShareSDK.initSDK(AddFriendsActivity.this);
		setContentView(R.layout.activity_add_friends);

		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		// btn_saoyisao=(LinearLayout)this.findViewById(R.id.saoyisao);
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});
		this.findViewById(R.id.qq).setOnClickListener(this);
		this.findViewById(R.id.sinaweibo).setOnClickListener(this);
		this.findViewById(R.id.saoyisao).setOnClickListener(this);
		this.findViewById(R.id.mail).setOnClickListener(this);
		this.findViewById(R.id.facebook).setOnClickListener(this);
		this.findViewById(R.id.qzone).setOnClickListener(this);
		this.findViewById(R.id.weixin).setOnClickListener(this);
		this.findViewById(R.id.activity_add_friends_btn).setOnClickListener(
				this);
		// facebook
		// twitter
		// weixin
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		ShareSDK.stopSDK(AddFriendsActivity.this);
	}

	// 第一个是请求标记，第二个是返回标记
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
//		LogUtils.d("requestCode=" + requestCode + "/resultCode=" + resultCode);
		if (requestCode == 1 && resultCode == PhoneActivity.phone) {
			if (data != null) {
				User = data.getStringExtra("User");
				// data.getStringExtra("PhoneNumber");

				PhoneNumber = data.getStringExtra("PhoneNumber");

//				LogUtils.d("User=" + User + "PhoneNumber=" + PhoneNumber);
				share(4);
			}
		}
		switch (requestCode) {
		case 2:
			if (data != null) {
				String result = data.getStringExtra("result");
//				   
				if (result != null) {

					erweimasourse = result;
					// EnterWebView(erweimasourse);
					String space = Constants.ErWeiMa_Space;
					String club = Constants.ErWeiMa_Club;
					//    
					//    
					if (erweimasourse.startsWith(space) == true) {
						int ll = erweimasourse.indexOf(".html");
						int spaceLenth = space.length();

						String uid = erweimasourse.substring(spaceLenth, ll);
						if (!StringUtil.isNullOrEmpty(uid)) {
							if (uid.equals(Utils
									.getUid(AddFriendsActivity.this))) {
								Intent intent = new Intent(
										AddFriendsActivity.this,
										MyDataActivity.class);
								startActivity(intent);
							} else {
								Intent intent = new Intent(
										AddFriendsActivity.this,
										SeeOtherPeopleSpaceActivity.class);
								intent.putExtra("friend_id", uid);
								startActivity(intent);
							}

						}

						// if (erweimasourse.indexOf("l") != -1) {
						// try {
						// String id = erweimasourse.substring(2,
						// erweimasourse.indexOf("l"));
						// String type = erweimasourse.substring(
						// erweimasourse.indexOf("l") + 1,
						// erweimasourse.indexOf("l") + 2);
						//    
						// if (type.equals("g")) {
						// if (id.equals(Utils
						// .getUid(AddFriendsActivity.this)) == true) {
						// Intent intent = new Intent(
						// AddFriendsActivity.this,
						// MyDataActivity.class);
						// intent.putExtra("uid", id);
						// startActivity(intent);
						// } else {
						// Intent intent = new Intent(
						// AddFriendsActivity.this,
						// DataErWeiMaActivity.class);
						// intent.putExtra("uid", id);
						// startActivity(intent);
						// }
						//
						// } else if (erweimasourse.indexOf("c") != -1) {
						// Intent intent = new Intent(
						// AddFriendsActivity.this,
						// ClubDataHuiYuanActivity.class);
						// intent.putExtra("uid", id);
						// startActivity(intent);
						// } else {
						// EnterWebView(erweimasourse);
						// }
						//
						// } catch (Exception e) {
						// // TODO: handle exception
						// }
						// }
					} else if (erweimasourse.startsWith(club) == true) {
						int ll = erweimasourse.indexOf(".html");

						int clubLenth = club.length();
						String cid = erweimasourse.substring(clubLenth, ll);
						if (!StringUtil.isNullOrEmpty(cid)) {
							Intent intent = new Intent(AddFriendsActivity.this,
									ClubHomepageActivity.class);
							intent.putExtra("cid", cid);
							startActivity(intent);
						}
					} else {
						EnterWebView(erweimasourse);
					}
				}
			}
			break;

		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.activity_add_friends_btn:
			Intent intent = new Intent(AddFriendsActivity.this,
					Search_Friends_Activity.class);
			startActivity(intent);
			break;
		case R.id.qq:
			share(0);
			break;
		case R.id.sinaweibo:
			share(1);
			break;
		case R.id.mail:
			// share(4);
			// Intent itt = new Intent(AddFriendsActivity.this,
			// PhoneActivity.class);
			// startActivityForResult(itt, 1);
			share(4);

			break;
		case R.id.facebook:
			share(3);
			break;
		case R.id.qzone:
			share(2);
			break;
		case R.id.weixin:
			share(5);
			break;
		case R.id.saoyisao:
			Intent it = new Intent(AddFriendsActivity.this,
					CaptureActivity.class);
			startActivityForResult(it, 2);

			intent = null;
			break;
		}
		if (intent != null) {
			startActivity(intent);
			intent = null;
		}
	}

	/**
	 * 分享
	 * 
	 * @param 0:qq,1:sina,2,qzone,3.facebook;4.短信 5wechat
	 */
	public void share(int num) {
		sp = new ShareParams();

		share = null;
		switch (num) {
		case 0:// QQ
			sp.setText(getResources().getString(R.string.wx2_14));
			sp.setTitle(getResources().getString(R.string.Share));
			sp.setTitleUrl(Constants.share_no_image_share_address);
			sp.setImageUrl(Constants.share_no_image_share_address);
			share = ShareSDK.getPlatform(AddFriendsActivity.this, QQ.NAME);
			break;
		case 1:// sinaweibo
			sp.setText(getResources().getString(R.string.wx2_14));

			sp.setImageUrl(Constants.share_no_image_share_address);
			share = ShareSDK.getPlatform(AddFriendsActivity.this,
					SinaWeibo.NAME);
			break;
		case 2:// QZone title titleUrl text site siteUrl
			sp.setText(getResources().getString(R.string.wx2_14));
			sp.setTitle(getResources().getString(R.string.Share));
			sp.setTitleUrl(Constants.share_no_image_share_address);
			sp.setSite(getResources().getString(R.string.wx2_14));
			sp.setSiteUrl(Constants.share_no_image_share_address);
			sp.setImageUrl(Constants.share_no_image_share_address);
			share = ShareSDK.getPlatform(AddFriendsActivity.this, QZone.NAME);
//			LogUtils.d("运行到了这里325");
			break;
		case 3:// Facebook
			sp.setText(getResources().getString(R.string.wx2_14));
			share = ShareSDK
					.getPlatform(AddFriendsActivity.this, Facebook.NAME);
			break;
		case 4:// ShortMessage
			sp.setAddress("");
			sp.setText(getResources().getString(R.string.wx2_14));
			sp.setTitle(getResources().getString(R.string.Share));
			sp.setImageUrl(Constants.share_no_image_share_address);

			share = ShareSDK.getPlatform(AddFriendsActivity.this,
					ShortMessage.NAME);
			break;
		case 5:// Wechat
			sp.setText(getResources().getString(R.string.wx2_14));
			sp.setTitle(getResources().getString(R.string.Share));
			sp.setImageUrl(Constants.share_no_image_share_address);
			sp.setAddress("" + PhoneNumber);
			// qq空间的必须要的两个
			sp.setSite(getResources().getString(R.string.wx2_14));
			sp.setImageUrl(Constants.share_no_image_share_address);
			sp.setShareType(Wechat.SHARE_TEXT);
			// 这才是分享过去的链接，用户点击他后进入链接
			sp.setTitleUrl(getResources().getString(R.string.wx2_15));
			share = ShareSDK.getPlatform(AddFriendsActivity.this, Wechat.NAME);
			break;
		}
		share.setPlatformActionListener(new PlatformActionListener() {

			@Override
			public void onError(Platform platform, int action, Throwable t) {
				// TODO Auto-generated method stub
				// if (action == Platform.ACTION_USER_INFOR) {
				sharehanders.sendEmptyMessage(MSG_AUTH_ERROR);
				// LogUtils.i("834");
				// }
//				LogUtils.d("运行到了这里344 action=" + action + "/t=" + t);
			}

			@Override
			public void onComplete(Platform platform, int arg1,
					HashMap<String, Object> arg2) {
				// TODO Auto-generated method stub
//				LogUtils.d("运行到了这里351");
				Message msg = new Message();
				msg.what = 7;

				Bundle bun = new Bundle();
				bun.putString("name", platform.getName());
				msg.setData(bun);

				sharehanders.sendMessage(msg);
			}

			@Override
			public void onCancel(Platform platform, int arg1) {
				// TODO Auto-generated method stub
//				LogUtils.d("运行到了这里357");
				// sharehanders.sendEmptyMessage(8);
			}
		}); // 设置分享事件回调
		share.SSOSetting(false);
		share.showUser(null);
		outerShareUrl(AddFriendsActivity.this, "friend",
				Utils.getUid(AddFriendsActivity.this), "0",
				Utils.getUid(AddFriendsActivity.this), num);
	}

	/**
	 * 站外分享返回相应链接----POST
	 * 
	 * @param $type
	 *            分享类型 photo_img：相片 humor_trends:心情动态 record_article：记录（记）
	 *            club:创建的俱乐部 activity：发起的活动 friend：朋友
	 * @param $uid
	 *            被分享的内容所属的用户
	 * @param $cid
	 *            被分享的内容所属的俱乐部 个人内容时$cid=0
	 * @param $conId
	 *            被分享的内容ID
	 * @param $num
	 *            num是确定当前分享的是什么
	 * */
	public void outerShareUrl(Context ct, final String type, final String uid,
			final String cid, final String conId, final int num) {

		// CommonUtils.CommomPostfunction(ct, Constants.BadiUrl_1 + "/"
		// + "web/outerShareUrl", map, sharehanders, 0, 0, 5, 6);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("type", type);
				map.put("cid", cid);
				map.put("conId", conId);
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "web/outerShareUrl");
				//    
				if (content != null) {
					Results results = Utils.checkResult_NNN(
							AddFriendsActivity.this, content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    
						try {
							// list = JSONUtils.getListByJsonString(
							// results.getRetmsg(),
							// Pre_message_total.class);

							if (results.isRet() == true) {
								Message msg = new Message();
								msg.what = 5;
								Bundle bun = new Bundle();
								bun.putString("msg", results.getRetmsg());
								bun.putInt("num", num);
								msg.setData(bun);

								sharehanders.sendMessage(msg);
							} else {
								Message msg = new Message();
								msg.what = 5;
								Bundle bun = new Bundle();
								bun.putString("msg", results.getRetmsg());
								bun.putInt("num", num);
								msg.setData(bun);
								sharehanders.sendMessage(msg);
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
							sharehanders.sendEmptyMessage(6);
						}
					} else {
						sharehanders.sendEmptyMessage(0);
					}
				} else {
					sharehanders.sendEmptyMessage(0);
				}

			}
		});
	}
	// private void showShare(boolean silent, String platform) {
	// final OnekeyShare oks = new OnekeyShare();
	// oks.setNotification(R.drawable.ic_launcher,getResources().getString(R.string.app_name));
	// oks.setAddress("12345678901");
	// oks.setTitle(getResources().getString(R.string.evenote_title));
	// oks.setTitleUrl("http://sharesdk.cn");
	// oks.setText(getResources().getString(R.string.share_content));
	// oks.setImagePath(AddFriendsActivity.TEST_IMAGE);
	// oks.setImageUrl(MainActivity.TEST_IMAGE_URL);
	// oks.setUrl("http://www.sharesdk.cn");
	// oks.setFilePath(MainActivity.TEST_IMAGE);
	// oks.setComment(getContext().getString(R.string.share));
	// oks.setSite(getContext().getString(R.string.app_name));
	// oks.setSiteUrl("http://sharesdk.cn");
	// oks.setVenueName("ShareSDK");
	// oks.setVenueDescription("This is a beautiful place!");
	// oks.setLatitude(23.056081f);
	// oks.setLongitude(113.385708f);
	// oks.setSilent(silent);
	// if (platform != null) {
	// oks.setPlatform(platform);
	// }
	// // 取消注释，可以实现对具体的View进行截屏分享
	// // oks.setViewToShare(getPage());
	//
	// // 去除注释，可令编辑页面显示为Dialog模式
	// // oks.setDialogMode();
	//
	// // 去除注释，在自动授权时可以禁用SSO方式
	// // oks.disableSSOWhenAuthorize();
	//
	// // 去除注释，则快捷分享的操作结果将通过OneKeyShareCallback回调
	// // oks.setCallback(new OneKeyShareCallback());
	// oks.setShareContentCustomizeCallback(new ShareContentCustomizeDemo());
	//
	// // 去除注释，演示在九宫格设置自定义的图标
	// // Bitmap logo = BitmapFactory.decodeResource(menu.getResources(),
	// R.drawable.ic_launcher);
	// // String label = menu.getResources().getString(R.string.app_name);
	// // OnClickListener listener = new OnClickListener() {
	// // public void onClick(View v) {
	// // String text = "Customer Logo -- ShareSDK " +
	// ShareSDK.getSDKVersionName();
	// // Toast.makeText(menu.getContext(), text, Toast.LENGTH_SHORT).show();
	// // oks.finish();
	// // }
	// // };
	// // oks.setCustomerLogo(logo, label, listener);
	//
	// // 去除注释，则快捷分享九宫格中将隐藏新浪微博和腾讯微博
	// // oks.addHiddenPlatform(SinaWeibo.NAME);
	// // oks.addHiddenPlatform(TencentWeibo.NAME);
	//
	// oks.show(getContext());
	// }
}
